// settings for easy customization
var server_address = ""; // your server address (removes address prompt and connects to server directly) (address:port)
var menu_visible = false; // changes menu visibility on startup (true/false)
var clear_on_send = "Off"; // default selection for clear-on-send setting ("Off"/"On")
var show_message_timestamps = "On"; // default selection for Timestamps setting ("Off"/"On")
var settings_save = "Off"; // default selection for Settings save setting ("Off"/"On")

// generate initial random username
let nickname_digits = Math.round( Math.random() * 1000 );
var nickname = "user" + nickname_digits;
document.getElementById("nickname-input").value = nickname;

// trying to load cookies to get settings and nickname
console.log(document.cookie);
let raw_cookies = document.cookie.split("=")[1];

console.log(raw_cookies);

try {
	let cookies = JSON.parse(raw_cookies);

	if (cookies != undefined && cookies != "") {
		try {
			if (cookies["settings_save"] == "On") {
				if (cookies["nickname"] != undefined) {
					globalThis.nickname = cookies["nickname"];
					document.getElementById("nickname-input").value = nickname;
				}
				if (cookies["clear_on_send"] != undefined) globalThis.clear_on_send = cookies["clear_on_send"];
				if (cookies["show_message_timestamps"] != undefined) globalThis.show_message_timestamps = cookies["show_message_timestamps"];
				if (cookies["settings_save"] != undefined) globalThis.settings_save = cookies["settings_save"];
			}
		} catch (e) {
			console.log(e);
		}
	}
}
catch (e) {
	console.log(e);
}

// update nickname fron the gui (browser)
function changeNickname(new_nick) {
	nickname = new_nick;

	if (settings_save == "On") {
		// doing full settings save
		settings_backup = {
			"nickname": nickname,
			"clear_on_send": clear_on_send,
			"show_message_timestamps": show_message_timestamps,
			"settings_save": settings_save
		};

		new_cookie = JSON.stringify(settings_backup);
		document.cookie = "settings=" + new_cookie;
	}

	console.log("Switched username to " + new_nick);
}

// send message through gui (browser)
function sendMessage(message_content) {
	if (connection_send_opened) {
		var new_message = {
			"data": {
				"nickname": nickname,
				"content": message_content,
			}
		};

		send_socket.send( JSON.stringify(new_message) );
		console.log("Sent " + new_message);

		// clearing text field with respect to clear-on-send setting
		if (clear_on_send == "On") document.getElementById("text-input").value = "";
	} else {
		alert("Connection is not opened yet; not sending message");
	}
}

function sendMessageButton() {
	sendMessage( document.getElementById("text-input").value );
}

// adding listener for Enter key
document.getElementById("text-input").addEventListener("keydown", function (event) {
	if (event.keyCode == 13) { sendMessage( document.getElementById("text-input").value );	}
});

// adding listener for settings button
function toggle_settings_visibility() {
	menu_visible = !menu_visible;
	if (menu_visible) document.getElementById("settings-menu").style.display = "block";
	else document.getElementById("settings-menu").style.display = "none";
}

// visual changes when buttons are clicked
function change_clear_on_send(element) {
	// change variable accordingly
	clear_on_send = element.innerHTML;

	// clearing selection class from every option in the container
	var children = element.parentElement.children;

	for (var i = 0; i < children.length; i++) {
		try {
			children[i].classList.remove("option-selected");
		} catch { /* pass */ }
	}

	if (settings_save == "On") {
		// doing full settings save
		settings_backup = {
			"nickname": nickname,
			"clear_on_send": clear_on_send,
			"show_message_timestamps": show_message_timestamps,
			"settings_save": settings_save
		};

		new_cookie = JSON.stringify(settings_backup);
		document.cookie = "settings=" + new_cookie;
	}

	// giving it to the selected option
	element.classList.add("option-selected");
}

function change_timestamps(element) {
	// change variable accordingly
	show_message_timestamps = element.innerHTML;

	// clearing selection class from every option in the container
	var children = element.parentElement.children;

	for (var i = 0; i < children.length; i++) {
		try {
			children[i].classList.remove("option-selected");
		} catch { /* pass */ }
	}

	if (settings_save == "On") {
		// doing full settings save
		settings_backup = {
			"nickname": nickname,
			"clear_on_send": clear_on_send,
			"show_message_timestamps": show_message_timestamps,
			"settings_save": settings_save
		};

		new_cookie = JSON.stringify(settings_backup);
		document.cookie = "settings=" + new_cookie;
	}

	// giving it to the selected option
	element.classList.add("option-selected");
}

function change_settings_save(element) {
	// change variable accordingly
	settings_save = element.innerHTML;

	// clearing selection class from every option in the container
	var children = element.parentElement.children;

	for (var i = 0; i < children.length; i++) {
		try {
			children[i].classList.remove("option-selected");
		} catch { /* pass */ }
	}

	// doing full settings save
	settings_backup = {
		"nickname": nickname,
		"clear_on_send": clear_on_send,
		"show_message_timestamps": show_message_timestamps,
		"settings_save": settings_save
	};

	new_cookie = JSON.stringify(settings_backup);
	document.cookie = "settings=" + new_cookie;

	// giving it to the selected option
	element.classList.add("option-selected");
}

// render default settings selections
if (clear_on_send == "Off") document.getElementById("inner-1.1").classList.add("option-selected");
else document.getElementById("inner-1.2").classList.add("option-selected");

if (show_message_timestamps == "Off") document.getElementById("inner-2.1").classList.add("option-selected");
else document.getElementById("inner-2.2").classList.add("option-selected");

if (settings_save == "Off") document.getElementById("inner-3.1").classList.add("option-selected");
else document.getElementById("inner-3.2").classList.add("option-selected");

// defining send_socket globally
var send_socket = "";

// making sure messages are not being sent before connection properly opens
var connection_send_opened = false;

// connect to the server (as listener-basic)
function connect_listen(address) {
	let listen_socket = new WebSocket("ws://" + address);

	listen_socket.onopen = function (e) {
		let role_definition = JSON.stringify("listener_basic");
		listen_socket.send(role_definition);

		console.log("Connection_listen successfull!");	
	};

	listen_socket.onmessage = function (event) {
		console.log("New event: " + event.data);
		let message = JSON.parse(event.data);

		// creating and rendering new message on the screen
		var new_message_container = document.createElement("div");
		new_message_container.className = "message-container";

		var name = document.createElement("span");
		name.className = "username-box";
		name.innerHTML = message["data"]["nickname"];
		new_message_container.appendChild(name);

		if (show_message_timestamps == "On") {
			var timestamp = document.createElement("span");
			timestamp.className = "timestamp-box";

			// making nice timestamp format
			d = new Date(message["timestamp_server"]*1000);
			timestamp.innerHTML = d.getFullYear() + ".";
			if ((d.getMonth() + 1) < 10) { timestamp.innerHTML += 0 };
			timestamp.innerHTML += (d.getMonth() + 1) + ".";
			if ((d.getDate()) < 10) { timestamp.innerHTML += 0 };
			timestamp.innerHTML += d.getDate() + " ";
			if (d.getHours() < 10) { timestamp.innerHTML += 0 };
			timestamp.innerHTML += d.getHours() + ":";
			if (d.getMinutes() < 10) { timestamp.innerHTML += 0 };
			timestamp.innerHTML += d.getMinutes() + ":";
			if (d.getSeconds() < 10) { timestamp.innerHTML += 0 };
			timestamp.innerHTML += d.getSeconds();

			new_message_container.appendChild(timestamp);
		}

		var br = document.createElement("br");
		new_message_container.appendChild(br);

		var text = document.createElement("span");
		text.className = "content-box";
		text.innerHTML = message["data"]["content"];
		new_message_container.appendChild(text);

		document.getElementById("message-list").appendChild(new_message_container);
	};

	listen_socket.onclose = function (e) {
		console.log("Connection_listen closed");
	}
}

// connect to the server (as sender-basic)
function connect_send(address) {
	send_socket = new WebSocket("ws://" + address);

	send_socket.onopen = function (e) {
		let role_definition = JSON.stringify("sender_basic");
		send_socket.send(role_definition);

		console.log("Connection_send successfull!");

		globalThis.connection_send_opened = true;
	};

	send_socket.onclose = function (e) {
		console.log("Connection_send closed");
	};
}

// prompting for server address if it's
// not set by server operator through
// easy settings (server_address variable)

// this doesn't have proper interface so
// it just uses good old prompt() for now
if (server_address == "") {
	server_address = prompt("Server address", "");
}

connect_listen(server_address);
connect_send(server_address);
